<template>
  <div>
    <el-dialog title="告警处理" :visible.sync="dialogVisible" width="480px" :before-close="closeAddDialog"
      :modal-append-to-body="false" :close-on-click-modal="false" :modal="true">
      <!-- <div
        style="
          font-size: 22px;
          color: #ffffff;
          margin-bottom: 30px;
          padding-left: 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <el-button
          size="mini"
          type="primary"
          @click="addErasure"
          v-if="
            alarmInfo.deviceType == 'SmokeAlarm' &&
            (alarmInfo.alarmType == 5 || alarmInfo.alarmType == 1) &&
            flag
          "
          >消音下发</el-button
        >
      </div> -->
      <el-form :model="ruleForm" :rules="rules" ref="refalarmHandleInfo" label-width="110px" label-position="top">

        <el-form-item size="small" label="告警类型" prop="alarmFactor">
          <el-radio v-model="ruleForm.alarmFactor" label="真实告警">真实告警</el-radio>
          <el-radio v-model="ruleForm.alarmFactor" label="误报" style="margin-left: 20px">误报</el-radio>
          <el-radio v-model="ruleForm.alarmFactor" label="测试" style="margin-left: 20px">测试</el-radio>
          <el-radio v-if="detail.parentDeviceCode" v-model="ruleForm.alarmFactor" label="转工单"
            style="margin-left: 20px">转工单</el-radio>
        </el-form-item>

        <el-form-item size="small" v-if="
          ruleForm.alarmFactor == '真实告警' &&
          (user.tenantId == '1762803843806539777' ||
            user.tenantId == '1770292338296893442' ||
            user.tenantId == '1772837590137270273')
        ">
          <el-collapse accordion v-model="activeName">
            <!-- <el-collapse-item title="通知对象" name="1">
              <div v-for="(item, index) in responderList" :key="index" v-if="index < 10">
                <span style="margin-right: 15px">{{ item.mobile }}</span><span>{{ item.name }}</span>
              </div>
            </el-collapse-item> -->
            <el-collapse-item name="1">
              <template slot="title">
                <div class="custom-title">
                  <span>火情电话通知（{{ responderList.length }}人）</span>
                  <el-tooltip placement="bottom">
                    <div slot="content">
                      确认真实火灾可立即拨打语音告警通知整栋楼所有的接警人。<br />语音通知模板内容：<br />业主请注意，现在XX位置发生火情。现场火情控制中，请不<br />要惊慌，有序通过疏散楼梯撤离到安全地带，疏散时不要拥挤<br />，优先照顾好老人、孩子和妇女，疏散时不要乘坐电梯，谢谢。
                    </div>
                    <el-button class="el_button"><i class="iconfont wenhao" style="color: #cfd3ec"></i></el-button>
                  </el-tooltip>
                  <el-radio v-model="ruleForm.responder" label="是" style="margin-left: 10px">是</el-radio>
                  <el-radio v-model="ruleForm.responder" label="否">否</el-radio>
                </div>
              </template>
              <div v-for="(item, index) in responderList" :key="index" v-if="index < 10">
                <span style="margin-right: 15px">{{ item.mobile }}</span><span>{{ item.name }}</span>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>

        <!-- <el-form-item size="small" label="是否消音" prop="alarmFactor"  v-if="
            alarmInfo.deviceType == 'SmokeAlarm' &&
            (alarmInfo.alarmType == 5 || alarmInfo.alarmType == 1) && ruleForm.alarmFactor=='误报'
          ">
          <el-radio v-model="ruleForm.erasure" label="是">是</el-radio>
          <el-radio v-model="ruleForm.erasure" label="否" style="margin-left: 20px;">否</el-radio>
        </el-form-item> -->

        <el-form-item size="small" label="处理人" v-if="ruleForm.alarmFactor == '转工单'" prop="handleUserId">
          <el-select v-model="ruleForm.handleUserId" filterable placeholder="请选择处理人" style="width: 100%" size="small"
            clearable>
            <el-option v-for="(item, i) in fcrDutyUserRelatedVO" :key="i" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item size="small" label="抄送人" v-if="ruleForm.alarmFactor == '转工单'">
          <el-select v-model="ruleForm.userIds" filterable multiple collapse-tags placeholder="请选择抄送人"
            style="width: 100%" size="small" clearable>
            <el-option v-for="(item, i) in fcrDutyUserRelatedVO" :key="i" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item size="small" label="反馈内容" v-if="ruleForm.alarmFactor != '转工单'">
          <el-input maxlength="30" rows="3" type="textarea" v-model="ruleForm.feedback" resize="none"
            :autosize="{ minRows: 2, maxRows: 5 }"></el-input>
        </el-form-item>

        <el-form-item size="small" label="照片" v-if="ruleForm.alarmFactor != '转工单'">
          <div>
            <el-upload :class="{ disabled: uploadDisabled }" :on-remove="handleRemove" :on-change="uploadSectionFile"
              :action="baseUrl" list-type="picture-card" accept=".jpg,.png" :on-preview="handlePictureCardPreview"
              :headers="headers" :before-upload="beforeAvatarUpload" :on-success="handleSuccessFunction" :limit="1"
              :on-exceed="handleExceedScene" :file-list="fileList">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="addSubmit" v-preventReClick="1000">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 二次确认 -->
    <el-dialog title="确认提示" :visible.sync="dialogVisibleFinish" width="480px" :before-close="closeDialogFinish"
      :modal-append-to-body="false" :close-on-click-modal="false" :modal="true">
      <div>
        {{ describe }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitFinish" v-preventReClick="1000">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="照片" :visible.sync="dialogVisible2" :before-close="closeDialogFinish2"
      :modal-append-to-body="false" :close-on-click-modal="false" :modal="true">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {
  reqAlarmHandle,
  reqAlarmHandleResult,
  reqCommand,
  reqClosedLoop,
} from "@/api/api";
import { reqGetBuildingReceiver, reqFire } from "@/api/apiDatav";
import { mapState } from "vuex";
import asc from "@utils/asc.js"; //加密解密
import { log } from "ezuikit-js";

export default {
  props: ["alarmInfo", "detail", "fcrDutyUserRelatedVO"],
  data() {
    return {
      activeName: "1",
      flag: true, //消音下发
      radio: "1",
      fileList: [],
      headers: {
        token: asc.decrypt(sessionStorage.getItem("token")),
      },
      dialogImageUrl: "",
      ruleForm: {
        alarmFactor: "真实告警",
        feedback: "",
        pic: "",
        userId: "",
        erasure: "是",
        responder: "是",
        handleUserId: "",
        userIds: [],
      },
      dialogVisible: false,
      // 表单验证规则
      rules: {
        alarmFactor: [
          {
            required: true,
            message: "请选择告警类型",
            trigger: ["blur", "change"],
          },
        ],
        handleUserId: [
          {
            required: true,
            message: "请选择处理人",
            trigger: "change",
          },
        ],
      },
      alarmFactorList: [
        {
          id: 0,
          name: "火警",
        },
        {
          id: 1,
          name: "误报",
        },
        {
          id: 2,
          name: "测试",
        },
        {
          id: 3,
          name: "其他",
        },
      ],
      restaurants: [],
      uploadDisabled: false, //加号默认显示
      dialogVisible2: false,
      responderList: [],

      dialogVisibleFinish: false, //二次确认弹窗
      describe:
        "开启火情电话通知会立即发送ai火警语音至所有通知对象，确认是否立即通知？",
    };
  },
  computed: {
    ...mapState(["user", "datav"]),
  },
  watch: {
    dialogVisible(e) {
      if (e) {
        this.flag = true;
      }
    },
    // 'ruleForm.responder'(e) {
    //   // console.log(e);
    //   // if (e == '是') {
    //   //   this.activeName = '1'
    //   // } else {
    //   //   this.activeName = ''
    //   // }
    // }
  },
  methods: {
    setalarmFactor(e) {
      if (e == 2) {
        this.ruleForm.alarmFactor = "误报";
      } else {
        this.ruleForm.alarmFactor = "真实告警";
        if (
          this.user.tenantId == "1762803843806539777" ||
          this.user.tenantId == "1770292338296893442" ||
          this.user.tenantId == "1772837590137270273"
        ) {
          // 汇九川
          this.getreqGetBuildingReceiver();
        }
      }
    },
    // 安装点获取所属建筑物所有接警人
    async getreqGetBuildingReceiver() {
      const res = await reqGetBuildingReceiver(this.alarmInfo.spaceId);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // console.log(res);
      this.responderList = res.data.rows || [];
    },
    uploadSectionFile(file, fileList) {
      if (fileList.length >= 1) {
        this.uploadDisabled = true; //隐藏加号
      }
    },
    //删除照片
    handleRemove(file) {
      this.ruleForm.pic = "";
      setTimeout(() => {
        this.uploadDisabled = false;
      }, 1000);
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    loadAll() {
      return [
        { value: "火警" },
        { value: "误报" },
        { value: "测试" },
        { value: "其它" },
      ];
    },
    handleSelect(item) {
      // console.log(item);
    },
    // 清除告警因素
    clearAlarmFactor() {
      this.restaurants = this.loadAll();
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },
    // 上传文件之前的钩子
    beforeAvatarUpload(file) {
      let isJPG = true;
      let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        this.uploadDisabled = false;
        this.$modal.notifyWarning("图片只能是 jpg/png 格式!");
        isJPG = false;
        return isJPG;
      } else if (!isLt) {
        this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
        this.uploadDisabled = false;
        isJPG = false;
      }
      return isJPG;
    },
    // 上传成功
    handleSuccessFunction(response, file, fileList) {
      this.ruleForm.pic = file.response.data.url;
    },
    // 文件超出个数限制时的钩子
    handleExceedScene() {
      this.$modal.notifyWarning(`照片只能上传一张`);
    },
    // 处理告警弹窗点击确认
    addSubmit() {
      this.$refs.refalarmHandleInfo.validate(async (valid) => {
        if (!valid) return;
        if (
          (this.ruleForm.alarmFactor == "真实告警" ||
            this.ruleForm.alarmFactor == "误报") &&
          (this.user.tenantId == "1762803843806539777" ||
            this.user.tenantId == "1770292338296893442" ||
            this.user.tenantId == "1772837590137270273")
        ) {
          if (this.ruleForm.alarmFactor == "误报") {
            this.describe = "是否确认为误报！";
          } else {
            if (this.ruleForm.responder == "是") {
              this.describe =
                "此操作将会通过电话通知所有相关人员，请谨慎操作！";
            } else {
              this.describe = "是否确认此操作！";
            }
          }
          this.dialogVisibleFinish = true;
        } else {
          await this.reqAlarmHandleFun();
        }
      });
    },
    // 点击关闭弹框
    closeAddDialog() {
      this.uploadDisabled = false;
      this.fileList = [];
      this.ruleForm = {
        alarmFactor: "真实告警",
        feedback: "",
        pic: "",
        userId: "",
        erasure: "是",
        responder: "是",
        userIds: []
      };
      this.$refs.refalarmHandleInfo.resetFields();
      this.dialogVisible = false;
      // this.$emit("clickflag");
    },

    // 处理告警请求
    async reqAlarmHandleFun() {
      let params = {}
      if (this.ruleForm.alarmFactor == '转工单') {
        if (this.ruleForm.handleUserId == '') return this.$modal.notifyWarning('请选择处理人');
        params = {
          id: this.alarmInfo.id,
          alarmFactor: this.ruleForm.alarmFactor,
          userId: this.user.userId,
          userIds: this.ruleForm.userIds || [],
          handleUserId: this.ruleForm.handleUserId,
        }
      } else {
        params = {
          id: this.alarmInfo.id,
          alarmFactor: this.ruleForm.alarmFactor,
          feedback: this.ruleForm.feedback,
          pic: this.ruleForm.pic,
          userId: this.user.userId,
        }
      }
      const res = await reqAlarmHandle(params);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // 第一次处理，如果是未处理告警则-1
      if (this.alarmInfo.status == 1) {
        this.datav.sum = !this.datav.sum;
        this.$store.commit("saveSum", this.datav.sum); //未处理告警-1
      }
      this.ruleForm.feedback = "";
      if (
        this.user.tenantId == "1762803843806539777" ||
        this.user.tenantId == "1770292338296893442" ||
        this.user.tenantId == "1772837590137270273"
      ) {
        // 汇九川逻辑
        if (this.ruleForm.alarmFactor != '转工单') {
          await this.reqClosedLoopFun(); // 告警完结请求
          this.$emit("updateAlarmList", this.alarmInfo.id, '3'); // 处理成功后更新告警列表
        } else {
          this.$emit("updateAlarmList", this.alarmInfo.id, '2'); // 处理成功后更新告警列表
        }
        if (this.ruleForm.responder == "是") {
          await this.reqFireFun(); // 火警通知整栋楼的接警人请求
        }
      } else {
        if (this.ruleForm.alarmFactor != '转工单') {
          await this.reqClosedLoopFun(); // 告警完结请求
          this.$emit("updateAlarmList", this.alarmInfo.id, '3'); // 处理成功后更新告警列表
        } else {
          this.$emit("updateAlarmList", this.alarmInfo.id, '2'); // 处理成功后更新告警列表
        }
      }
      this.$modal.notifySuccess("处理成功");
      await this.closeAndUpdateFun();
      this.dialogVisibleFinish = false;
    },
    // 告警完结请求
    async reqClosedLoopFun() {
      let res2 = await reqClosedLoop({
        id: this.alarmInfo.id,
      });
      if (res2.code !== 20000) return this.$modal.notifyWarning(res2.message);
      this.datav.end = !this.datav.end;
      this.$store.commit("saveEnd", this.datav.end); //完结后处理中-1
    },

    // 火警通知整栋楼的接警人请求
    async reqFireFun() {
      const res2 = await reqFire(this.alarmInfo.id);
      if (res2.code !== 20000) return this.$modal.notifyWarning(res2.message);
    },

    // 确认告警后关闭弹窗+实时告警列表更新
    closeAndUpdateFun() {
      this.closeAddDialog(); //关闭告警处理弹窗
      this.$parent.cancelAddDia(); //关闭设备告警信息弹窗
    },

    // 二次确认确认
    async submitFinish() {
      await this.reqAlarmHandleFun();
      // await this.reqFireFun();// 火警通知整栋楼的接警人请求
      // await this.reqClosedLoopFun();
      // this.closeAndUpdateFun();
      // this.dialogVisibleFinish = false;
    },
    closeDialogFinish() {
      this.dialogVisibleFinish = false;
    },
    closeDialogFinish2() {
      this.dialogVisible2 = false;
    },
    // 消音下发
    addErasure() {
      this.$confirm("是否确认下发消音，消音后九十秒内报警不会响铃!", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await reqCommand({
            serviceType: "muffling_cmd",
            serviceValue: 1,
            imei: this.alarmInfo.imei,
            deviceId: this.alarmInfo.deviceId,
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("下发消音成功！");
          this.flag = false;
        })
        .catch(() => { });
    },
  },
  mounted() {
    this.restaurants = this.loadAll();
  },
  created() {
    this.baseUrl = `${this.$baseURL_copy}file/upload`;
  },
};
</script>

<style lang="less" scoped>
// @import url("../../common.less");

// 隐藏加号
/deep/ .disabled .el-upload--picture-card {
  display: none !important;
}

// 二次确认弹窗样式
::v-deep .el-dialog__body {
  background: #35437e !important;
  min-height: 50px !important;
  // height: 200px !important;
}

// 弹窗样式
::v-deep .el-dialog {
  // height: 400px !important;
}

::v-deep .el-dialog__footer {
  background: #35437e !important;
}

::v-deep .el-button.el-button--default {
  background: #17286a !important;
  border: 1px solid #17286a !important;
  color: #d1d1d1 !important;
}

::v-deep .el-button.el-button--primary {
  background: #000f4a !important;
  border: 1px solid #00edfe !important;
  color: #d1d1d1 !important;
}

::v-deep .el-input__inner {
  background: #01101d !important;
}

::v-deep .el-textarea__inner {
  background: #01101d !important;
  resize: none;
}

::v-deep .el-upload--picture-card {
  // width: 75px;
  // height: 75px;
  // line-height: 85px;
  background: #01101d;
  border: none;
}

// 单选按钮
::v-deep .el-radio__input.is-checked+.el-radio__label {
  color: #7367f0;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #7367f0;
  background: #7367f0;
}

/* 未选中状态的样式 */
::v-deep .el-radio {
  color: #cfd3ec;
}

// 折叠
::v-deep .el-collapse-item__header {
  background: #fff;
  border: none;
}

::v-deep .el-collapse-item__wrap {
  border: none;
}

// 折叠
.el-collapse {
  width: 100%;
  border-top: none;
  border-bottom: none;
}

::v-deep .el-collapse-item__header {
  color: #cfd3ec;
  font-size: 14px;
  background-color: transparent;
  border: none;
  border-radius: 5px !important;
}

::v-deep .el-collapse-item__content {
  color: #fff;
  font-size: 13px;
  border: none !important;
  padding: 0;
  background-color: transparent !important;
  border-radius: 0 0 5px 5px !important;
  max-height: 16vh;
  overflow-y: auto;
}

::v-deep .el-collapse-item__wrap {
  border: none;
  background-color: transparent;
}

::v-deep .el_button.el-button {
  background: transparent !important;
  border: transparent !important;
}

::v-deep .el-collapse-item__arrow {
  margin: 0 0px 0 auto;
}

.custom-title {
  display: flex;
  align-items: baseline;
}

/* 定义滚动条样式 */
::v-deep .el-collapse-item__content::-webkit-scrollbar {
  display: block;
  width: 8px; //定义滚动条宽度
  height: 10px; //定义滚动条高度
  border-radius: 10px; //定义滚动条圆角
  // background-color: red; //定义滚动条颜色
}

/*定义滚动条轨道 内阴影+圆角*/
::v-deep .el-collapse-item__content::-webkit-scrollbar-track {
  box-shadow: inset 0 0 0px rgba(240, 240, 240, 0.5); //定义轨道阴影
  border-radius: 10px; //定义轨道圆角
  background-color: #04306f; //定义轨道颜色
}

/*定义滑块 内阴影+圆角*/
::v-deep .el-collapse-item__content::-webkit-scrollbar-thumb {
  border-radius: 10px; //定义滑块圆角
  box-shadow: inset 0 0 0px rgba(240, 240, 240, 0.5); //定义滑块阴影
  background-color: #0270ad; //定义滑块颜色
}
</style>
